package fu.k4c.vTeam.Manage;

import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.gson.Gson;

import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Controller.VlocationItemizedOverlay;
import fu.k4c.vTeam.Main.ViewEventActivity;
import fu.k4c.vTeam.Object.AccentRemover;
import fu.k4c.vTeam.Object.CreateLocationStatus;

public class CreateEventActivity extends MapActivity {
	Button btn_endtime, btn_startdate, btn_starttime, btn_enddate;
	String mStartTime, mEndTime, mStartDate, mEndDate;
	MapView mMapview;
	String email;
	VlocationItemizedOverlay mMyOverlay;
	LocationManager mLocationManager;
	LocationListener mLocationListener;
	String city = "";
	String category = "196";
	GeoPoint gp3 = new GeoPoint(21032757, 105849667);
	GeoPoint gp = new GeoPoint(21032757, 105849667);
	GeoPoint gp2 = new GeoPoint(10830608, 106631927);
	/** Called when the activity is first created. */
	String cities[] = { "Hà Nội", "TP Hồ Chí Minh", "Khác" };
	DateFormat fmtstartDate = DateFormat.getDateInstance();
	DateFormat fmtstartTime = DateFormat.getTimeInstance();
	DateFormat fmtendDate = DateFormat.getDateInstance();
	DateFormat fmtendTime = DateFormat.getTimeInstance();
	Calendar cstartTime = Calendar.getInstance();
	Calendar cendTime = Calendar.getInstance();
	Calendar cstartDate = Calendar.getInstance();
	Calendar cendDate = Calendar.getInstance();
	ProgressDialog proDialog;
	DatePickerDialog.OnDateSetListener d1 = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			cstartDate.set(Calendar.YEAR, year);
			cstartDate.set(Calendar.MONTH, monthOfYear);
			cstartDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			String date = getMonth(monthOfYear + 1) + " " + getDay(dayOfMonth)
					+ "," + year;
			btn_startdate.setText(date);
		}
	};
	DatePickerDialog.OnDateSetListener d2 = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			cendDate.set(Calendar.YEAR, year);
			cendDate.set(Calendar.MONTH, monthOfYear);
			cendDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			String date = getMonth(monthOfYear + 1) + " " + getDay(dayOfMonth)
					+ "," + year;
			btn_enddate.setText(date);
		}
	};
	TimePickerDialog.OnTimeSetListener t1 = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			cstartTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
			cstartTime.set(Calendar.MINUTE, minute);
			btn_starttime.setText(fmtstartTime.format(cstartTime.getTime()));
		}
	};
	TimePickerDialog.OnTimeSetListener t2 = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			cendTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
			cendTime.set(Calendar.MINUTE, minute);
			btn_endtime.setText(fmtendTime.format(cendTime.getTime()));
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_event_activity);
		overridePendingTransition(android.R.anim.fade_in,
				android.R.anim.fade_out);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
		Bundle data = getIntent().getExtras();
		if (data != null) {
			email = data.getString("email");
		}
		mMapview = (MapView) findViewById(R.id.map_create_event_activity);
		mMapview.getController().setZoom(8);
		mMapview.setSatellite(false);
		GeoPoint p = new GeoPoint(21032757, 105849667);
		mMapview.getController().animateTo(p);
		mMyOverlay = new VlocationItemizedOverlay(this.getResources()
				.getDrawable(R.drawable.point));
		OverlayItem newplace = new OverlayItem(p, "New Place", "New Location");
		mMyOverlay.addOverlay(newplace);
		mMapview.getOverlays().add(mMyOverlay);
		mMapview.invalidate();
		mMapview.getOverlays().add(new Overlay() {
			@Override
			public boolean onTap(GeoPoint p, MapView arg1) {
				// TODO Auto-generated method stub
				mMyOverlay.clear();
				mMapview.invalidate();
				mMapview.getController().animateTo(p);
				gp = p;
				OverlayItem newplace = new OverlayItem(p, "New Place",
						"New Location");
				mMyOverlay.addOverlay(newplace);
				mMapview.invalidate();
				return super.onTap(p, arg1);
			}

		});
		mMapview.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent ev) {
				// TODO Auto-generated method stub
				switch (ev.getAction()) {
				case MotionEvent.ACTION_DOWN:
					mMapview.requestDisallowInterceptTouchEvent(true);
					break;
				case MotionEvent.ACTION_UP:
					mMapview.requestDisallowInterceptTouchEvent(false);
					break;
				}
				return false;
			}
		});
		Spinner Cityspinner = (Spinner) findViewById(R.id.sp_create_event_activity_provide);
		ArrayAdapter<String> spinnerArrayAdapter1 = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, cities);
		spinnerArrayAdapter1
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		Cityspinner.setAdapter(spinnerArrayAdapter1);
		Cityspinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						Object item = parent.getItemAtPosition(pos);
						city = item.toString();
						if (city.equals("Hà Nội")) {
							mMyOverlay.clear();
							mMapview.invalidate();
							mMapview.getController().setZoom(14);
							GeoPoint p1 = new GeoPoint(21032757, 105849667);
							mMapview.getController().animateTo(p1);
							OverlayItem newplace = new OverlayItem(p1,
									"New Place1", "New Location1");
							mMyOverlay.addOverlay(newplace);
							mMapview.invalidate();
						} else if (city.equals("TP Hồ Chí Minh")) {
							mMyOverlay.clear();
							mMapview.invalidate();
							mMapview.getController().setZoom(14);
							GeoPoint p2 = new GeoPoint(10830608, 106631927);
							mMapview.getController().animateTo(p2);
							OverlayItem newplace = new OverlayItem(p2,
									"New Place2", "New Location2");
							mMyOverlay.addOverlay(newplace);
							mMapview.invalidate();
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
		btn_starttime = (Button) findViewById(R.id.btn_create_event_activity_starttime);
		btn_startdate = (Button) findViewById(R.id.btn_create_event_activity_startdate);
		btn_endtime = (Button) findViewById(R.id.btn_create_event_activity_endtime);
		btn_enddate = (Button) findViewById(R.id.btn_create_event_activity_enddate);
		btn_startdate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new DatePickerDialog(CreateEventActivity.this, d1, cstartDate
						.get(Calendar.YEAR), cstartDate.get(Calendar.MONTH),
						cstartDate.get(Calendar.DAY_OF_MONTH)).show();
			}
		});
		btn_enddate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				new DatePickerDialog(CreateEventActivity.this, d2, cendDate
						.get(Calendar.YEAR), cendDate.get(Calendar.MONTH),
						cendDate.get(Calendar.DAY_OF_MONTH)).show();
			}
		});
		btn_starttime.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				new TimePickerDialog(CreateEventActivity.this, t1, cstartTime
						.get(Calendar.HOUR_OF_DAY), cstartTime
						.get(Calendar.MINUTE), true).show();
			}
		});
		btn_endtime.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				new TimePickerDialog(CreateEventActivity.this, t2, cendTime
						.get(Calendar.HOUR_OF_DAY), cendTime
						.get(Calendar.MINUTE), true).show();
			}
		});
		Button btn_back = (Button) findViewById(R.id.btn_create_event_activity_back);
		btn_back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(CreateEventActivity.this,
						ViewEventActivity.class);
				setResult(RESULT_CANCELED, i);
				finish();
			}
		});
		Button btn_submit = (Button) findViewById(R.id.btn_create_event_activity_create);
		btn_submit.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				String mCity = city;
				EditText et_address = (EditText) findViewById(R.id.et_create_event_activity_address);
				String mAddress = et_address.getText().toString();
				EditText et_place_name = (EditText) findViewById(R.id.et_create_event_activity_name);
				String mPlaceName = et_place_name.getText().toString();
				String mCategory = category;
				EditText et_phone_number = (EditText) findViewById(R.id.et_create_event_activity_phone);
				String mPhone = et_phone_number.getText().toString();
				EditText et_detail = (EditText) findViewById(R.id.et_create_event_activity_place_detail);
				String mDetail = et_detail.getText().toString();
				if (cstartDate.compareTo(cendDate) == 1) {
					Toast.makeText(getApplicationContext(),
							"Ngày kết thúc không hợp lệ", Toast.LENGTH_LONG)
							.show();
				} else if (cstartDate.compareTo(cendDate) == 0) {
					if (cstartTime.compareTo(cendTime) == 1) {
						Toast.makeText(getApplicationContext(),
								"Giờ kết thúc không hợp lệ", Toast.LENGTH_LONG)
								.show();
					} else if (cstartTime.compareTo(cendTime) == 0) {
						Toast.makeText(getApplicationContext(),
								"Giờ kết thúc không hợp lệ", Toast.LENGTH_LONG)
								.show();
					}
				} else {
					mStartTime = fmtstartTime.format(cstartTime.getTime());
					mStartDate = fmtstartDate.format(cstartDate.getTime());
					mEndTime = fmtendTime.format(cendTime.getTime());
					mEndDate = fmtendDate.format(cendDate.getTime());
				}

				if (mAddress.equals("")) {
					Toast.makeText(getApplicationContext(),
							"Bạn phải nhập địa chỉ", Toast.LENGTH_LONG).show();
				} else if (mPlaceName.equals("")) {
					Toast.makeText(getApplicationContext(),
							"Bạn phải nhập tên sự kiện", Toast.LENGTH_LONG)
							.show();
				} else if (mPhone.equals("")) {
					Toast.makeText(getApplicationContext(),
							"Bạn phải nhập số điện thoại", Toast.LENGTH_LONG)
							.show();
				} else if (mDetail.equals("")) {
					Toast.makeText(getApplicationContext(),
							"Bạn phải nhập 1 số thông tin về sự kiện",
							Toast.LENGTH_LONG).show();
				} else if (gp.equals(gp2) || gp.equals(gp3)) {
					Toast.makeText(getApplicationContext(),
							"Bạn phải chọn nơi sự kiện diễn ra trên bản đồ",
							Toast.LENGTH_LONG).show();
				} else {
					if (mCity.equals("Hà Nội")) {
						mCity = "1";

					} else if (mCity.equals("TP Hồ Chí Minh")) {
						mCity = "2";
					} else if (mCity.equals("Khác")) {
						mCity = "3";
					}

					try {
						proDialog = ProgressDialog.show(
								CreateEventActivity.this, "",
								"Đang kết nối đến máy chủ...");
						new Thread() {
							public void run() {

								try {
									sleep(1000);

								} catch (Exception e) {
									System.out.print(e.toString());
								}
								proDialog.dismiss();
							}
						}.start();
						String StartDate="";
						String EndDate = "";
						
						if (btn_startdate.getText()
								.toString().toLowerCase()
							.indexOf("thg") >= 0){
							StartDate = convertDay(btn_startdate.getText()
								.toString());
							EndDate = convertDay(btn_enddate.getText()
								.toString());
							mStartTime = convertTime(mStartTime);
							mEndTime = convertTime(mEndTime);
						}else {
							StartDate = btn_startdate.getText()
									.toString();
							EndDate = btn_enddate.getText()
									.toString();
						}
						SchemeRegistry registry = new SchemeRegistry();
						registry.register(new Scheme("http", PlainSocketFactory
								.getSocketFactory(), 80));
						HttpParams httpParams = new BasicHttpParams();
						ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
								httpParams, registry);
						HttpClient client = new DefaultHttpClient(connMgr,
								httpParams);
						HttpPost post = new HttpPost(
								getString(R.string.connectionString)
										+ "vLocationService/addlocation");
						post.setHeader("Accept", "application/json");
						post.setHeader("Content-type", "application/json");
						HashMap<String, Object> postParameters = new HashMap<String, Object>();
						postParameters.put("Descriptiontextcs", mDetail);
						postParameters.put("address", mAddress);
						postParameters.put("categoryID", mCategory);
						postParameters.put("citiID", mCity);
						postParameters.put("email", email);
						postParameters.put("latitude", gp.getLatitudeE6() / 1E6);
						postParameters.put("longitude",
								gp.getLongitudeE6() / 1E6);
						AccentRemover aremover = new AccentRemover();
						String mnamesearch = aremover.removeAccent(mPlaceName)
								.replace(" ", "");
						String mnameurl = aremover.removeAccent(mPlaceName)
								.replace(" ", "-");
						postParameters.put("namesearch", mnamesearch);
						postParameters.put("nameurl", mnameurl);
						postParameters.put("phone", mPhone);
						postParameters.put("placename", mPlaceName);
						postParameters.put("startTime", mStartTime);
						postParameters.put("startDate", StartDate);
						postParameters.put("endTime", mEndTime);
						postParameters.put("endDate", EndDate);
						Gson gson = new Gson();		
						String jsonParameters = gson.toJson(postParameters);
						System.out.println(jsonParameters);
						post.setEntity(new StringEntity(jsonParameters, "UTF-8"));
						HttpResponse response = client.execute(post);
						HttpEntity entity = response.getEntity();
						String jsonresult = EntityUtils.toString(entity);
						System.out.println(jsonresult);
						CreateLocationStatus status = gson.fromJson(jsonresult,
								CreateLocationStatus.class);
						if (status.getCreateplacestatus().equals("Eventmember")) {
							Toast.makeText(getApplicationContext(),
									"Sự kiện đang được kiểm duyệt",
									Toast.LENGTH_LONG).show();
							Intent i = new Intent(CreateEventActivity.this,
									ViewEventActivity.class);
							setResult(RESULT_OK, i);
							finish();
						} else if (status.getCreateplacestatus().equals(
								"Eventadmin")) {
							Toast.makeText(getApplicationContext(),
									"Đã tạo sự kiện thành công",
									Toast.LENGTH_LONG).show();
							Intent i = new Intent(CreateEventActivity.this,
									ViewEventActivity.class);
							setResult(RESULT_OK, i);
							finish();
						}
					} catch (Exception e) {
						Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
					}
				}
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent i = new Intent(CreateEventActivity.this,
					ViewEventActivity.class);
			setResult(RESULT_CANCELED, i);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	public String getMonth(int month) {
		return new DateFormatSymbols().getShortMonths()[month - 1];
	}

	public String getDay(int day) {
		if (day < 10) {
			return "0" + day;
		}
		return "" + day;
	}
	public String convertDay(String dayConvert){
		String day = "";
		String[] day1 = dayConvert.split(" ");
		
		if (day1[1].equals("1")) {
			day = "Jan " + day1[2];
		}else if (day1[1].equals("2")){
			day = "Feb " + day1[2];
		}else if (day1[1].equals("3")){
			day = "Mar " + day1[2];
		}else if (day1[1].equals("4")){
			day = "Apr " + day1[2];
		}else if (day1[1].equals("5")){
			day = "May " + day1[2];
		}else if (day1[1].equals("6")){
			day = "Jun " + day1[2];
		
		}else if (day1[1].equals("7")){
			day = "Jul " + day1[2];
		}else if (day1[1].equals("8")){
			day = "Aug " + day1[2];
		}else if (day1[1].equals("10")){
			day = "Oct " + day1[2];
		}else if (day1[1].equals("11")){
			day = "Nov " + day1[2];
		}else if (day1[1].equals("12")){
			day = "Dec " + day1[2];
		}else if (day1[1].equals("9")){
			day = "Sep " + day1[2];
		}
		
		
		return day;
	}
	public String convertTime(String time){
		String mTime="";
		String[] timeArray = time.split(":");
		
		if (timeArray[0].equals("00")){
			mTime = "12:"+timeArray[1] +":"+timeArray[2]+" AM";
		}else if (Integer.parseInt(timeArray[0]) > 0 && Integer.parseInt(timeArray[0]) < 12 ){
			mTime = time + " AM";
		}else if (Integer.parseInt(timeArray[0]) > 11 && Integer.parseInt(timeArray[0]) < 24){
			if (Integer.parseInt(timeArray[0]) > 12){
				mTime = (Integer.parseInt(timeArray[0]) - 12) +":"+timeArray[1] +":"+timeArray[2]+ " PM";
			}else
				mTime = time + " PM";
		}
		return mTime;
	}

}
